package theTVDB.com.service
{

	import mx.rpc.http.HTTPService;

	public class Services
	{
		private static var services:Services = new Services();;

		public static function getInstance():Services
		{
			return services;
		}

		public function Services()
		{
			if (services != null)
				throw new Error( "Only one Services instance should be instantiated" );

			trace("Services created");

			mirrorList.method = "GET";
			mirrorList.resultFormat = "e4x";

			searchSeries.method = "GET";
			searchSeries.resultFormat = "e4x";

			_getSeries.method = "GET";
			_getSeries.resultFormat = "e4x";

			_getEpisode.method = "GET";
			_getEpisode.resultFormat = "e4x";
		}

		[Bindable] private var _APIKey:String;

		[Bindable] private var _xmlMirror:String = "http://www.thetvdb.com";
		[Bindable] private var _bannerMirror:String = "http://www.thetvdb.com";
		[Bindable] private var _zipMirror:String = "http://www.thetvdb.com";

		public var mirrorList:HTTPService = new HTTPService();
		public var searchSeries:HTTPService = new HTTPService();
		private var _getSeries:HTTPService = new HTTPService();
		private var _getEpisode:HTTPService = new HTTPService();

		public function set APIKey(key:String):void
		{
			_APIKey = key;
			BuildURLs();
		}
		
		public function get APIKey():String
		{
			return _APIKey;
		}

		public function UpdateMirrors():void
		{
			BuildURLs()
		}

		public function BuildURLs():void
		{
			mirrorList.url 	= _xmlMirror + "/api/" + _APIKey + "/mirrors.xml";
			searchSeries.url 	= _xmlMirror + "/api/GetSeries.php";
		}

		public function getSeries(seriesID:String, language:String = "en"):HTTPService
		{
			_getSeries.url = _xmlMirror + "/api/" + _APIKey + "/series/" + seriesID + "/" + language + ".xml";
			return _getSeries;
		}

		public function getEpisode(seriesID:String, season:int, episode:int, language:String = "en"):HTTPService
		{
			_getEpisode.url = _xmlMirror + "/api/" + _APIKey + "/series/" + seriesID + "/default/" + season.toString() + "/" + episode.toString() + "/" + language + ".xml";
			return _getEpisode;
		}

		public function getDefaultEpisode(seriesID:String, season:int, episode:int, language:String = "en"):HTTPService
		{
			return getEpisode(seriesID, season, episode, language);
		}

		public function getDVDEpisode(seriesID:String, season:int, episode:int, language:String = "en"):HTTPService
		{
			_getEpisode.url = _xmlMirror + "/api/" + _APIKey + "/series/" + seriesID + "/dvd/" + season.toString() + "/" + episode.toString() + "/" + language + ".xml";
			return _getEpisode;
		}

		public function getAbsoluteEpisode(seriesID:String, number:int, language:String = "en"):HTTPService
		{
			_getEpisode.url = _xmlMirror + "/api/" + _APIKey + "/series/" + seriesID + "/absolute/" + number.toString() + "/" + language + ".xml";
			return _getEpisode;
		}
	}
}
